import React, { Component } from 'react';

export default class ReactPdfJs extends Component {
  componentDidMount() {
    const { pdf, pageNumber } = this.props;
    this.drawPage(pdf, pageNumber);
  }

  componentWillReceiveProps(nextProps) {
    const { pageNumber } = this.props;
    if (nextProps.pageNumber !== pageNumber) {
      this.drawPage(nextProps.pdf, nextProps.pageNumber);
    }
  }

  drawPage = (pdf, pageNumber) => {
    pdf.getPage(pageNumber).then(page => {
      const scale = 1.25;
      const viewport = page.getViewport(scale);

      const { canvas } = this;
      const canvasContext = canvas.getContext('2d');
      canvas.height = viewport.height;
      canvas.width = viewport.width;

      const renderContext = {
        canvasContext,
        viewport,
      };
      page.render(renderContext);
    });
  };

  render() {
    return (
      <div style={{ textAlign: 'center', background: '#f2f2f2' }}>
        <canvas
          style={{ display: 'inline-block' }}
          ref={canvas => {
            this.canvas = canvas;
          }}
        />
      </div>
    );
  }
}
